package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"log"
	"os"
)

func main() {

	var bits int = 1024
	//flag.IntVar(&bits, "b", 2048, "密钥长度，默认为1024位")
	if err := GenRsaKey(bits); nil != err {
		log.Fatal("密钥文件生成失败！", err)
		return
	}
	log.Println("密钥文件生成成功！")

}

func GenRsaKey(bits int) error {

	// 生成私钥文件
	privateKey, err := rsa.GenerateKey(rand.Reader, bits)
	if nil != err {
		return err
	}

	// 与java兼容
	derStream, err := x509.MarshalPKCS8PrivateKey(privateKey) //x509.MarshalPKCS1PrivateKey(privateKey)
	if nil != err {
		return err
	}
	block := &pem.Block{
		Type:  "私钥",
		Bytes: derStream,
	}

	file, err := os.Create("d:/private1.pem")
	if nil != err {
		return err
	}

	err = pem.Encode(file, block)
	if nil != err {
		return err
	}

	// 生成公钥文件
	publicKey := &privateKey.PublicKey
	derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
	if nil != err {
		return err
	}

	block = &pem.Block{
		Type:  "公钥",
		Bytes: derPkix,
	}
	file, err = os.Create("d:/public1.pem")
	if nil != err {
		return err
	}

	err = pem.Encode(file, block)
	if nil != err {
		return err
	}
	return nil
}
